<?php

namespace Controller\Options;

class Ad extends \Controller\Base {

	public function actionIndex() {
		$this->setMenuPath('Options', 'Ad');
		if ($this->isPost()) {
			$this->save();
		}
		$id = $this->getInt('id');
		$ad = \Data\Ad::instance()->getById($id);
		$adList = \Data\Ad::instance()->findAll();
		$this->assign('ad', $ad);
		$this->assign('adList', $adList);
		$this->display();
	}

	private function save() {
		$data = array();
		$config = array(
			'savePath' => 'upload/' ,             //存储文件夹
			'maxSize' => 1024 * 2 ,                   //允许的文件最大尺寸，单位KB
			'allowFiles' => array( '.gif' , '.png' , '.jpg' , '.jpeg' )  //允许的文件格式
		);
		$type = $this->postInt('type');
		if (!$type) {
			$this->addErrorMsg('请选择广告类型');
			return;
		}
		$href = $this->postParam('href');
		$name = $this->postParam('name');
		$target = $this->postParam('target');
		$desc = $this->postParam('desc');
		$price = $this->postParam('price');
		//上传文件目录
		$path = COMMON_DIR . '/uploads/';
		//背景保存在临时目录中
		$config['savePath'] = $path;
		$up = new \Util\Uploader('upfile', $config);
		$id = $this->postInt('id');
		$oldSrc = $this->postParam('oldSrc');

		if (!empty($_FILES['upfile']['size'])) {
			$info = $up->getFileInfo();
			if ($info['state'] != 'SUCCESS') {
				$this->addErrorMsg($info['state']);
				return;
			}
			$info['url'] = urlencode(str_replace($path, '', $info['url']));
			$data['Src'] = $info['url'];
		} else {
			$data['Src'] = $oldSrc;
		}


		$data['Type'] = $type;
		$data['Name'] = $name;
		$data['Href'] = $href;
		$data['Target'] = $target;
		$data['Desc'] = $desc;
		$data['Price'] = $price;
		if ($id) {
			\Data\Ad::instance()->where(array('Id' => $id))->update($data);
			$this->addSuccessMsg('修改成功');
		} else {
			\Data\Ad::instance()->insert($data);
			$this->addSuccessMsg('添加成功');
		}
	}
}